<template>
  <div class="drug-management">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>药品信息管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 添加按钮 -->
    <div class="add-btn-container">
      <el-button type="primary" icon="el-icon-circle-plus" @click="openAddDialog" size="medium">
        添加药品信息
      </el-button>
    </div>

    <!-- 添加对话框 -->
    <el-dialog title="添加药品信息" :visible.sync="addDialogVisible" width="50%" :before-close="handleAddDialogClose">
      <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="120px">
        <el-form-item label="药品名称" prop="drugName">
          <el-input v-model="addForm.drugName"></el-input>
        </el-form-item>
        <el-form-item label="药品描述" prop="drugInfo">
          <el-input type="textarea" v-model="addForm.drugInfo" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="药品功效" prop="drugEffect">
          <el-input type="textarea" v-model="addForm.drugEffect" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="药品图片" prop="drugImg">
          <!-- 图片上传组件 -->
          <el-upload 
            class="upload-drug-image" 
            :action="uploadAction" 
            :headers="uploadHeaders"
            :show-file-list="false" 
            :on-success="handleAddImageSuccess"
            :before-upload="beforeAddImageUpload" 
            :disabled="addDialogLoading"
          >
            <el-button type="primary" :loading="addUploadLoading">上传图片</el-button>
            <div v-if="addForm.drugImg" class="image-preview">
              <img :src="addForm.drugImg" alt="预览图" class="preview-image" />
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="发布人" prop="publisher">
          <el-input v-model="addForm.publisher"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="addDialogLoading" @click="handleAddSave">保存</el-button>
      </div>
    </el-dialog>

    <!-- 搜索框 -->
    <el-input placeholder="查询（输入要查询的药品名称）" v-model="searchKeyword" class="search-input" @input="handleSearch"></el-input>

    <!-- 药品列表 -->
    <el-table :data="filteredDrugs" stripe style="width: 100%" v-loading="loading">
      <el-table-column prop="drugId" label="药品ID" sortable></el-table-column>
      <el-table-column prop="drugName" label="药品名称"></el-table-column>
      <el-table-column label="药品描述">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.drugInfo" placement="top">
            <div class="ellipsis-text">{{ scope.row.drugInfo || '-' }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="药品功效">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.drugEffect" placement="top">
            <div class="ellipsis-text">{{ scope.row.drugEffect || '-' }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="药品图片" width="100">
        <template slot-scope="scope">
          <img 
            v-if="scope.row.drugImg" 
            :src="scope.row.drugImg" 
            alt="药品图片" 
            class="drug-image" 
            @error="handleImageError(scope)"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="注册时间">
        <template slot-scope="scope">
          {{ formatDate(scope.row.createtime) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间">
        <template slot-scope="scope">
          {{ formatDate(scope.row.updatetime) }}
        </template>
      </el-table-column>
      <el-table-column label="发布人" prop="publisher"></el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-document" @click="viewDetails(scope.row)">查看</el-button>
          <el-button type="text" icon="el-icon-edit" @click="editDrug(scope.row)">编辑</el-button>
          <el-button type="text" icon="el-icon-delete" @click="delDrug(scope.row.drugId)" style="color: #F56C6C;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog title="编辑药品信息" :visible.sync="editDialogVisible" width="50%" :before-close="handleEditDialogClose">
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="120px">
        <el-form-item label="药品ID" prop="drugId">
          <el-input v-model="editForm.drugId" disabled></el-input>
        </el-form-item>
        <el-form-item label="药品名称" prop="drugName">
          <el-input v-model="editForm.drugName"></el-input>
        </el-form-item>
        <el-form-item label="药品描述" prop="drugInfo">
          <el-input type="textarea" v-model="editForm.drugInfo" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="药品功效" prop="drugEffect">
          <el-input type="textarea" v-model="editForm.drugEffect" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="药品图片" prop="drugImg">
          <!-- 编辑时的图片上传组件 -->
          <el-upload 
            class="upload-drug-image" 
            :action="uploadAction" 
            :headers="uploadHeaders"
            :show-file-list="false" 
            :on-success="handleEditImageSuccess"
            :before-upload="beforeEditImageUpload" 
            :disabled="editDialogLoading"
          >
            <el-button type="primary" :loading="editUploadLoading">上传图片</el-button>
            <div v-if="editForm.drugImg" class="image-preview">
              <img :src="editForm.drugImg" alt="预览图" class="preview-image" />
              <el-button type="text" @click="clearEditImage">删除预览</el-button>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="发布人" prop="publisher">
          <el-input v-model="editForm.publisher"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="editDialogLoading" @click="handleEditSave">保存</el-button>
      </div>
    </el-dialog>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination 
        @current-change="handleCurrentChange" 
        @size-change="handleSizeChange"
        :current-page="currentPage" 
        :page-size="pageSize" 
        :total="total" 
        layout="prev, pager, next, jumper"
        :disabled="loading"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import api from '@/api';

export default {
  name: 'DrugManagement',
  data() {
    return {
      uploadAction: 'http://127.0.0.1:8081/common/uploadminio', // 上传接口地址
      uploadHeaders: {
        // 若需要认证，可添加token
        // Authorization: `Bearer ${this.getToken()}`
      },
      drugs: [], // 药品数据
      filteredDrugs: [], // 过滤后的药品数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchKeyword: '',
      loading: false,
      searchTimer: null,
      editDialogVisible: false,
      editForm: {},
      editRules: {
        drugName: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
        drugInfo: [{ required: true, message: '请输入药品描述', trigger: 'blur' }],
        drugEffect: [{ required: true, message: '请输入药品功效', trigger: 'blur' }],
        publisher: [{ required: true, message: '请输入发布人', trigger: 'blur' }]
      },
      addDialogVisible: false,
      addForm: {
        drugName: '',
        drugInfo: '',
        drugEffect: '',
        drugImg: '',
        publisher: ''
      },
      addRules: {
        drugName: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
        drugInfo: [{ required: true, message: '请输入药品描述', trigger: 'blur' }],
        drugEffect: [{ required: true, message: '请输入药品功效', trigger: 'blur' }],
        publisher: [{ required: true, message: '请输入发布人', trigger: 'blur' }]
      },
      // 上传状态管理
      addUploadLoading: false,
      editUploadLoading: false,
      addDialogLoading: false,
      editDialogLoading: false
    };
  },

  mounted() {
    this.fetchDrugs();
  },

  methods: {
    // 图片加载失败处理（显示默认图）
    handleImageError(scope) {
      scope.row.drugImg = ''; // 清空无效图片URL
    },

    // 格式化日期
    formatDate(dateValue) {
      if (!dateValue) return '-';

      let date;
      // 处理时间戳
      if (typeof dateValue === 'string' && !isNaN(Number(dateValue)) && dateValue.length > 10) {
        date = new Date(Number(dateValue));
      }
      // 处理ISO格式字符串
      else if (typeof dateValue === 'string' && dateValue.includes('T')) {
        date = new Date(dateValue);
      }
      // 处理YYYY-MM-DD格式字符串
      else if (typeof dateValue === 'string' && dateValue.includes('-')) {
        date = new Date(dateValue.replace(/-/g, '/'));
      }
      // 处理Date对象
      else if (dateValue instanceof Date) {
        date = dateValue;
      }

      if (isNaN(date.getTime())) return '-';

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // 搜索处理（带防抖）
    handleSearch() {
      if (this.searchTimer) clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        if (!this.searchKeyword.trim()) {
          this.filteredDrugs = [...this.drugs];
          return;
        }
        const keyword = this.searchKeyword.toLowerCase();
        this.filteredDrugs = this.drugs.filter(item =>
          item.drugName && item.drugName.toLowerCase().includes(keyword)
        );
      }, 300);
    },

    // 获取药品数据
    async fetchDrugs() {
      this.loading = true;
      try {
        const params = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchKeyword
        };

        const response = await api.drug.getDrugs(params);

        if (response.code === 0) {
          this.drugs = response.data.list || [];
          this.filteredDrugs = [...this.drugs];
          this.total = response.data.total || 0;
        } else {
          this.$message.error(response.message || '获取药品数据失败');
        }
      } catch (error) {
        console.error('请求出错:', error);
        this.$message.error('数据加载失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },

    // 分页变化
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchDrugs();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.fetchDrugs();
    },

    // 查看详情
    viewDetails(row) {
      console.log('查看详情:', row);
    },

    // 编辑药品
    editDrug(row) {
      this.editForm = JSON.parse(JSON.stringify(row));
      this.editDialogVisible = true;
    },

    // 关闭编辑对话框前重置表单状态
    handleEditDialogClose() {
      this.$refs.editFormRef && this.$refs.editFormRef.resetFields();
      this.editForm = {};
    },

    // 保存编辑内容
    async handleEditSave() {
      const isValid = await new Promise(resolve => {
        this.$refs.editFormRef.validate(valid => resolve(valid));
      });
      if (!isValid) return;

      try {
        this.editDialogLoading = true;
        const response = await api.drug.update(this.editForm);

        if (response.code === 0) {
          this.$message.success('修改成功');
          this.editDialogVisible = false;
          this.fetchDrugs();
        } else {
          this.$message.error(response.message || '修改失败');
        }
      } catch (error) {
        console.error('修改请求出错:', error);
        this.$message.error('修改失败，请稍后重试');
      } finally {
        this.editDialogLoading = false;
      }
    },

    // 打开添加对话框
    openAddDialog() {
      this.addDialogVisible = true;
      this.addForm = {
        drugName: '',
        drugInfo: '',
        drugEffect: '',
        drugImg: '',
        publisher: ''
      };
    },

    // 关闭添加对话框前重置表单状态
    handleAddDialogClose() {
      this.$refs.addFormRef && this.$refs.addFormRef.resetFields();
      this.addForm = {
        drugName: '',
        drugInfo: '',
        drugEffect: '',
        drugImg: '',
        publisher: ''
      };
    },

    // 保存新增药品
    async handleAddSave() {
      const isValid = await new Promise(resolve => {
        this.$refs.addFormRef.validate(valid => resolve(valid));
      });
      if (!isValid) return;

      try {
        this.addDialogLoading = true;
        const response = await api.drug.add(this.addForm);

        if (response.code === 0) {
          this.$message.success('添加成功');
          this.addDialogVisible = false;
          this.fetchDrugs();
        } else {
          this.$message.error(response.message || '添加失败');
        }
      } catch (error) {
        console.error('添加请求出错:', error);
        this.$message.error('添加失败，请稍后重试');
      } finally {
        this.addDialogLoading = false;
      }
    },

    // 删除药品
    async delDrug(drugId) {
      try {
        await this.$confirm('确定要删除这个药品信息吗？', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        this.loading = true;
        const response = await api.drug.delete({ drugId });

        if (response.code === 0) {
          this.$message.success('删除成功');
          if (this.drugs.length === 1 && this.currentPage > 1) {
            this.currentPage -= 1;
          }
          this.fetchDrugs();
        } else {
          this.$message.error(response.message || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error);
          this.$message.error('删除失败，请稍后重试');
        }
      } finally {
        this.loading = false;
      }
    },

    // 新增药品图片上传成功处理
    handleAddImageSuccess(response, file) {
      this.addUploadLoading = false;
      // 假设后端返回格式：{ code: 200, data: { url: '图片URL' }, message: '成功' }
      if (response.code === 200) {
        this.addForm.drugImg = response.data.url;
        this.$message.success('图片上传成功');
      } else {
        this.$message.error(response.message || '图片上传失败');
      }
    },

    // 新增药品图片上传前校验
    beforeAddImageUpload(file) {
      this.addUploadLoading = true;
      const isImage = /^image\/(jpeg|png|gif)$/.test(file.type);
      const isLessThan5M = file.size / 1024 / 1024 < 5;
      
      if (!isImage) {
        this.addUploadLoading = false;
        this.$message.error('只能上传JPG、PNG或GIF格式的图片');
        return false;
      }
      
      if (!isLessThan5M) {
        this.addUploadLoading = false;
        this.$message.error('图片大小不能超过5MB');
        return false;
      }
      
      return true;
    },

    // 编辑药品图片上传成功处理
    handleEditImageSuccess(response, file) {
      this.editUploadLoading = false;
      if (response.code === 200) {
        this.editForm.drugImg = response.data.url;
        this.$message.success('图片上传成功');
      } else {
        this.$message.error(response.message || '图片上传失败');
      }
    },

    // 编辑药品图片上传前校验
    beforeEditImageUpload(file) {
      this.editUploadLoading = true;
      const isImage = /^image\/(jpeg|png|gif)$/.test(file.type);
      const isLessThan5M = file.size / 1024 / 1024 < 5;
      
      if (!isImage) {
        this.editUploadLoading = false;
        this.$message.error('只能上传JPG、PNG或GIF格式的图片');
        return false;
      }
      
      if (!isLessThan5M) {
        this.editUploadLoading = false;
        this.$message.error('图片大小不能超过5MB');
        return false;
      }
      
      return true;
    },

    // 编辑时清除图片
    clearEditImage() {
      this.editForm.drugImg = '';
    }
  }
};
</script>

<style lang="less" scoped>
.drug-management {
  padding: 20px;

  .search-input {
    margin-bottom: 15px;
  }

  .el-table {
    margin-bottom: 15px;

    .drug-image {
      width: 60px;
      height: 60px;
      object-fit: cover;
      border-radius: 4px;
      vertical-align: middle;
    }

    .ellipsis-text {
      max-width: 200px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .pagination {
    text-align: center;
    margin-top: 20px;
  }

  .add-btn-container {
    margin: 15px 0;
    display: flex;
    justify-content: flex-end;
  }

  .upload-drug-image {
    display: flex;
    align-items: center;
    
    .el-upload {
      margin-right: 20px;
    }
    
    .image-preview {
      display: flex;
      align-items: center;
      
      .preview-image {
        width: 100px;
        height: 100px;
        object-fit: cover;
        border-radius: 4px;
        margin-right: 10px;
      }
    }
  }
}
</style>